package cn.bdqn.layui.controller;

import cn.bdqn.layui.entity.Menu;
import cn.bdqn.layui.entity.vo.MenuRoleVO;
import cn.bdqn.layui.service.menu.MenuService;
import cn.bdqn.layui.util.ResponseResult;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class MenuController {

    @Resource
    MenuService menuService;

    @RequestMapping("/quan/cai")
    public String menuhtml() {
        return "/views/user/menu/menu.html";
    }

    @RequestMapping("/menulist")
    @ResponseBody
    public String menulist(String menuName, Integer page, Integer limit) {
        page = page == null ? 1 : page;
        limit = limit == null ? 10 : limit;
        List<Menu> menus = menuService.findMenuPage(menuName, (page - 1) * limit, limit);
        int count = menuService.findMenuPageCount(menuName);
        JSONObject object = new JSONObject();
        object.put("code", 0);
        object.put("msg", "");
        object.put("data", menus);
        object.put("count", count);
        return object.toJSONString();
    }

    @RequestMapping("/toUpdateMenu")
    public String addMenu(Integer id, Model model) {
        Menu menu = menuService.findMenuById(id);
        model.addAttribute("menu", menu);
        return "/views/user/menu/menuform";
    }

    @RequestMapping("/updateMenu")
    @ResponseBody
    public ResponseResult updateMenu(Menu menu) {
        int i = menuService.updateMenu(menu);
        return new ResponseResult(200, "", i);
    }

    @RequestMapping("/toAddMenu")
    public String toAddMenu(Model model) {
        List<Menu> menuList = menuService.findByIdToParentId(0);
        model.addAttribute("<!--suppress ALL-->", menuList);
        return "/views/user/menu/menuform2";
    }

    @RequestMapping("/addMenu")
    public ResponseResult addMenu(Menu menu) {
        if (menu.getParentId() == -1) {
            menu.setParentId(0);
        }
        int i = menuService.addMeun(menu);
        return new ResponseResult(200, "", i);
    }

    @RequestMapping("/delMenu")
    @ResponseBody
    public ResponseResult delMenu(Integer id) {
        int i = menuService.delMenu(id);
        if (i > 0) {
            List<MenuRoleVO> roleVOList = menuService.findMenuRoleRid(0, id);
            for (MenuRoleVO vo : roleVOList) {
                menuService.delMeunRole(0, vo.getMid());
            }
        }
        return new ResponseResult(0, "", i);
    }

}
